<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../elementui/vue.min.js"></script>
    <link rel="stylesheet" href="../elementui/index.css">
    <script src="../elementui/index.js"></script>


</head>
<body>
<div id="app">

    <el-row>
        <textarea ref="textareaRef" cols="45" rows="7"></textarea>
    </el-row>
    <el-row>
        <el-button @click="createFile" type="primary">创建</el-button>
        <el-button @click="openFile" type="primary">打开</el-button>
        <el-button @click="saveAsFile(true)" type="primary">保存</el-button>
        <el-button @click="saveAsFile(false)" type="primary">另存为</el-button>
    </el-row>

</div>

<script type="module">
    new Vue({
        el: '#app',
        data: {
            object: {},
            handle: {},
        },
        methods: {
            setFileHandler(handle) {
                this.handle = handle
            },
            async createFile() {
                const opts = {
                    types: [
                        {
                            description: "Text file",
                            accept: {"text/plain": [".txt"]},
                        },
                    ],
                };
                let fileHandle = await window.showSaveFilePicker(opts);
                this.setFileHandler(fileHandle);
                return fileHandle;
            },
            async openFile() {
                let [fileHandle] = await window.showOpenFilePicker();
                this.setFileHandler(fileHandle);
                const f = await fileHandle.getFile()
                this.$refs.textareaRef.value = await f.text();
            },
            async saveFile(handle) {
                if (!handle) return;
                const stream = await this.handle.createWritable();
                await stream.write(this.$refs.textareaRef.value);
                await stream.close();

            },
            async saveAsFile(isSave) {
                const filehandle = await (isSave && !!this.handle)
                    ? this.handle
                    : await this.createFile();
                this.saveFile(filehandle);
            },
        }
    })
</script>
</body>
</html>
